package com.jt;

import com.sun.xml.internal.bind.v2.model.core.ID;
import redis.clients.jedis.Jedis;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 单点登录Demo
 * 1）完成用户身份认证
 * 2）完成用户资源访问授权
 * SSO系统具体实现
 * 1）用户登录成功后将登录状态信息存储到redis，要返回用户一个token。(UUID)
 * 2)用户登陆成功，可携带token访问资源，资源服务器检查token有效性，假如有效则访问。
 * 3)判定用户是否有资源的访问权限
 */
public class SSODemo01 {
    //执行登录逻辑
    public static String doLogin(String username,String password){
        //1.判定参数有效性
        if (username == null || "".equals(username))
            throw new IllegalArgumentException("user can not be empty");
        //2.判定用户是否存在(一般要查询数据库)
        if (!"tony".equals(username))
            throw new IllegalArgumentException("USER IS NULL");
        //3.判定密码是否正确(一般是要加密后比对)
        if (!"123456".equals(password))
            throw new IllegalArgumentException("password is not really");
        //4，将用户信息写入redis服务器
        Jedis jedis = JedisDataSource.getConnection();
        String token = UUID.randomUUID().toString();
        jedis.hset(token, "username", "tony");
        jedis.hset(token, "permission", "sys:res:view,sys:res:update");
        jedis.expire(token, 10);
        jedis.close();
        //5.返回token(UUID)
        return null;
    }
    //执行资源访问逻辑
    public static Object doGetResource(String token){
        //1.校验token是否为空
        if (token == null||"".equals(token))
            throw new IllegalArgumentException("请先登录");
        //2.基于token查询用户信息
        Jedis jedis = JedisDataSource.getConnection();
        Map<String, String> userMap = jedis.hgetAll(token);
        //3.判定用户是否已登录
        if (userMap == null || userMap.size()==0)
            throw new IllegalArgumentException("用户登录超时，重新登陆");
        //4.判定用户是否有资源的访问权限
        String permissionStr = userMap.get("permissions");
        if (permissionStr == null||"".equals(permissionStr))
            throw new RuntimeException("您无权访问这个资源");
        String[] permissionArray = permissionStr.split(",");
        List<String> permissions = Arrays.asList(permissionArray);
        if (!permissions.contains("sys:res:view"))
            throw  new RuntimeException("您无权访问这个资源");
        return "your resource";
    }
    public static void main(String[] args) {

        String username = "tony";
        String password = "123456";
        String token = doLogin(username, password);
        System.out.println("login success ,token is "+token);
        //2.携带token去访问资源
        //Thread.sleep(2000);
        Object resource = doGetResource(token);
        System.out.println(resource);

    }
}
